package com.hw01.common;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hw01.vo.LoginUserVo;

import java.net.URLDecoder;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理之前进行调用（Controller方法调用之前）
        System.out.println("拦截器：请求处理之前");

        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            for (Cookie cookie : cookies) {
                if ("userInfo".equals(cookie.getName())) {
                    String userInfo = URLDecoder.decode(URLDecoder.decode(cookie.getValue(), "UTF-8"), "UTF-8");

                    System.out.println(userInfo);

                    ObjectMapper mapper = new ObjectMapper();
                    LoginUserVo loginUser = mapper.readValue(userInfo, LoginUserVo.class);

                    UserInfo.set(loginUser);

                }
            }
        }
        // 这里可以添加你的业务逻辑，比如身份验证、权限校验等
        // 返回true继续请求，返回false中断请求
        return true;
    }
}